// pages/family/family.js
const app = getApp();
const util = require('../../utils/util.js');
const md5 = require('../../utils/md5.js');
const call = require('../../utils/request.js')
Page({

  /**
   * 页面的初始数据
   */
  data: {
    bodyHeight: app.globalData.sHeight,
    isLogin: false,
    userId: '',
    memberList: [],
    groupId: '',
    recipeTit: '早',
    recipes: {},
    currentRecipe: 0,
    currentRecipeList: [],
    privateList: []
  },
  onRecips() {
    wx.navigateTo({
      url: '/pages/family/recipes/recipes',
    })
  },
  onDetails(e) {
    const recipe = JSON.stringify(e.currentTarget.dataset.recipe);
    console.log('recipe', e.currentTarget.dataset.recipe);
    wx.navigateTo({
      url: '/pages/foodmanager/recipe/detail/detail?d_info=' + recipe,
    })
  },
  onLLL(e) {
    const list = e.currentTarget.dataset.recipeList;
    console.log('list', list)
    wx.navigateTo({
      url: '/pages/family/member/member?id=' + e.currentTarget.dataset.id,
    })
  },
  onCreate() {
    var that = this;
    wx.showModal({
      title: '提示',
      content: '确认要创建家庭么？',
      success(res1) {
        wx.getStorage({
          key: 'userId',
          success(res2) {
            console.log('userId', res2.data)
            if (res1.confirm) {
              that._addFamilyGroupDetailInfo(res2.data);
              that.setData({
                isLogin: true
              })
            }
          },
        })

      }
    })
  },
  onChangeCurrent(e) {
    this.setData({
      currentRecipe: e.detail.current
    })
  },
  onselect(e) {
    let that = this;
    // console.log('所选选项', e);
    const check = e.detail.current;
    const recipes = that.data.recipes;
    const currentRecipeList = check == '早' ? recipes.breakfasts : (check == '午' ? recipes.lunchs : recipes.dinners);
    this.setData({
      currentRecipe: 0,
      recipeTit: check,
      currentRecipeList: currentRecipeList,
      privateList: that._recipesFilter(currentRecipeList)
    }, () => {
      console.log('currentRecipeList', that.data.currentRecipeList)
    })
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {},
  onShow() {
   
  },
  _PermissionCheck(){
    let that = this;
    if (app.globalData.access_token){
      start();
    }else{
      app._getMac().then(i => {
        start();
      });
    }

    function start(){//页面初始化方法
      wx.getStorage({
        key: 'userId',
        success(res) {
          const userId = res.data;
          that.setData({
            userId: userId
          })
          console.log('userId', userId)
          that._getFamilyDetail(userId);
        },
        fail() {
          wx.setStorage({
            key: 'log',
            data: 'true',
          });
          wx.reLaunch({
            url: '/pages/login/login'
          })
        }
      })
    }
  },
  /**
   * 8)查询家庭群组信息（包括成员信息）
   */
  _getFamilyDetail() {
    console.log('开始查询')
    var that = this;
    const url = `/service/standard/v1/family/group/getFamilyDetail?access_token=${app.globalData.access_token}`;
    const params = {
      "header": app.globalData.reqHeader,
      "data": {
        "userId": that.data.userId
      }
    };
    console.log('调试1',params)
    call.postData(url, params,
      res => {
        console.log('查询成功');
        console.log('_getFamilyDetail_success', res);
        if (res.errormsg !== 'success') { //如果有异常状况，展示错误
          wx.showToast({
            title: res.errormsg,
            icon: 'none'
          })
        } else if (res.data.groupId) { //如果能查到群组Id，就展示页面
          this.setData({
            memberList: res.data.memberList,
            groupId: res.data.groupId,
            isLogin: true,
            groupId: res.data.groupId
          }, () => {
            that._getFamilyRecipes(); //获取到groupId之后，查询食材列表
          })
        }
      },
      err => {
        console.log('_getFamilyDetail_fail', err);
        wx.showToast({
          title: '网络好像开小差了哦~',
        });
      }, 'api')
  },
  /**
   * 47)用户创建家庭信息（同时创建管理员信息）
   */
  _addFamilyGroupDetailInfo(userId) {
    var that = this;
    const url = `/service/standard/v1/family/group/addFamilyGroupDetailInfo?access_token=${app.globalData.access_token}`;
    const params = {
      "header": app.globalData.reqHeader,
      "data": {
        "userId": userId,
        "groupName": 'family' + userId,
        "identityName": "群主",
        "nickName": 'nickname',
        "headImgUrl": app.globalData.userInfo.avatarUrl,
        "memberLabelInfo": {
          "mxb": [],
          "kwph": []
        }
      }
    }
    console.log('postman', url, JSON.stringify(params))
    call.postData(url, params,
      res => {
        console.log('_addFamilyGroupDetailInfo_success', res);
        if (res.errormsg !== 'success') { //创建失败的情况抛出
          wx.showToast({
            title: res.errormsg,
            icon: 'none'
          })
        } else {
          that._getFamilyDetail(userId); //创建成功之后立即获取家庭群组信息
        }
      },
      err => {
        console.log('_addFamilyGroupDetailInfo_fail', err);
        wx.showToast({
          title: '网络好像开小差了',
          icon: 'none'
        })
      }, 'api')
  },
  /**
   * 14)获取家庭的食谱推荐
   */
  _getFamilyRecipes() {
    let that = this;
    const url = `/service/standard/v1/family/getFamilyRecipes?access_token=${app.globalData.access_token}`;
    const params = {
      "header": app.globalData.reqHeader,
      "data": {
        "groupId": that.data.groupId
      }
    };
    call.postData(url, params,
      res => {
        console.log('_getFamilyRecipes_success', res);
        if (res.errormsg !== 'success') {
          wx.showToast({
            title: res.errormsg,
            icon: 'none'
          })
        } else {
          let currentRecipeList = [];
          const h = new Date().getHours();
          let tit = ''
          if (h < 10) {
            tit = '早'
            currentRecipeList = res.data.breakfasts
          } else if (h >= 10 && h <= 14) {
            tit = '午'
            currentRecipeList = res.data.lunchs
          } else {
            tit = '晚'
            currentRecipeList = res.data.dinners
          }
          that.setData({
            recipeTit: tit,
            recipes: res.data,
            currentRecipe: 0,
            currentRecipeList: currentRecipeList,
            privateList: that._recipesFilter(currentRecipeList)
          });
          that._recipesFilter(currentRecipeList);
        }
      },
      err => {
        console.log('_getFamilyRecipes_fail', err);
        wx.showToast({
          title: '网络好像出小差了',
          icon: 'none'
        })
      }, 'api')
  },
  /**
   * 菜谱过滤
   */
  _recipesFilter(currentRecipes) {
    const memberList = this.data.memberList.slice().map((m, i) => {
      m.personRecipeList = currentRecipes.filter((r) => {
        return r.memberInfos.find(i => i.memberInfoId == m.memberInfoId)
      }).slice(0, 3)
      return m
    });
    return memberList
  },
  /**
   * 删除家庭动作：1、删除家庭；2、打开删除窗口并提交验证码
   */
  onDelFamily(e) {
    let that = this;
    console.log('验证码', e.detail.mobileCode);
    if (e.detail.mobileCode) { //如果有了验证码，执行删除动作
      //调用删除接口把验证码发进去
      const url = `/service/standard/v1/family/group/deleteFamilyGroup?access_token=${app.globalData.access_token}`;
      const params = {
        "header": app.globalData.reqHeader,
        "data": {
          "userId": that.data.userId,
          "groupId": that.data.groupId,
          "securityCode": e.detail.mobileCode
        }
      };
      call.postData(url, params,
        res => {
          console.log('_deleteFamilyGroup_success', res);
          if (res.errormsg !== 'success') {
            wx.showToast({
              title: res.errormsg,
              icon: 'none',
              duration: 5000
            })
          } else {
            wx.showToast({
              title: '删除成功！',
              duration: 5000
            });
            that.setData({
              isOpenCode: false,
              mobileCode: ''
            });
            that._getFamilyDetail(); //重新查看信息
          }
        },
        err => {
          console.log('_deleteFamilyGroup_fail', err)
        }, 'api')
    } else {
      wx.showModal({
        title: '确认',
        content: '确定要删除该家庭么？',
        success(res) {
          if (res.confirm) {
            that.setData({
              isOpenCode: true,
              isSetting: false
            })
          }
        }
      })
    }
  }
})